<template>
  <gc-dialog
    :title="isEdit ? '编辑友链' : '新增友链'"
    :dialog-visible="true"
    @cancel="handleCancle"
    @ok="handleConfirm"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="友链名称" prop="name">
        <el-input type="text" v-model="form.name"  placeholder="请输入" />
      </el-form-item>
      <el-form-item label="友链地址" prop="link">
        <el-input type="text" v-model="form.link"  placeholder="请输入" />
      </el-form-item>
      <el-form-item label="友链Logo" prop="logo">
        <GcUploadImage :imageUrl="form.logo" @get-image="(url: string) => form.logo = url" />
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="OperateToolModal">
import { ref, reactive, computed, watch, type PropType } from 'vue'
import { ruleRequired, ruleMaxLength } from '@/utils/rules'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FriendLink } from '@/http/type'
import { apiCreateFriendLink, apiUpdateFriendLink } from '@/http/service'

const props = defineProps({
  friendLinkInfo: {
    type: Object as PropType<null | FriendLink>,
    default: () => null
  }
})
const emit = defineEmits(['close-modal'])
const formRef = ref<null | FormInstance>(null)
const form = reactive({
  name: '',
  link: '',
  logo: ''
})

const formRules = reactive<FormRules>({
  name: [ruleRequired('请输入友链名称'), ruleMaxLength(32)],
  link: [ruleRequired('请输入友链地址'), ruleMaxLength(255)],
  logo: [ruleRequired('请上传友链LOGO'), ruleMaxLength(255)]
})
const isEdit = computed(() => {
  return Boolean(props.friendLinkInfo)
})

async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    const API = isEdit.value ? apiUpdateFriendLink : apiCreateFriendLink
    await API(form)
    ElMessage.success(isEdit.value ? '编辑友链成功' : '新增友链成功')
    emit('close-modal', true)
  }
}

function handleCancle () {
  emit('close-modal')
}

watch(() => props.friendLinkInfo, val => {
  if (val) {
    const { id, name, link, logo } = val
    Object.assign(form, {
      id, name, link, logo
    })
  }
}, { immediate: true })
</script>

<style scoped lang="scss"></style>
